import { getCategoryTree } from "@/hooks";
import request from "..";

/**
 * 
 * 获取分类列表，优先从本地缓存中获取
 * @param refresh 
 * @returns 
 */
export const getCategoryList = async (refresh?:boolean):Promise<Category[]> => {
    const cache = localStorage.getItem('categoryList')
    //如果有本地缓存，且不刷新则返回格式化缓存数据
    if(cache && !refresh){
        return JSON.parse(cache)
    }else{
        const res = await request.get('/category');
        if(res.code === 200 && res.data){
            const tree = getCategoryTree(res.data,0)
            localStorage.setItem('categoryList',JSON.stringify(tree))
            return tree
        }else{
            return []
        }
    }
}
export const createCategory = async(data:any) => {
    const res = await request.post('/category',data);
    if(res.code === 200) getCategoryList(true)
    return res
}
export const updateCategory = async(id:number,data:any) => {
    const res = await request.put('/category/'+id,data);
    if(res.code === 200) getCategoryList(true)
    return res
}
export const deleteCategory = async(id:number) => {
    const res = await request.delete('/category/'+id);
    if(res.code === 200) getCategoryList(true)
    return res
}